'use strict';

exports.__esModule = true;

var _isFunction = require('lodash/isFunction');

var _isFunction2 = _interopRequireDefault(_isFunction);

var _isObject = require('lodash/isObject');

var _isObject2 = _interopRequireDefault(_isObject);

var _merge = require('lodash/merge');

var _merge2 = _interopRequireDefault(_merge);

var _isString = require('lodash/isString');

var _isString2 = _interopRequireDefault(_isString);

var _isPlainObject = require('lodash/isPlainObject');

var _isPlainObject2 = _interopRequireDefault(_isPlainObject);

var _customRequest = require('./customRequest');

var _customRequest2 = _interopRequireDefault(_customRequest);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var exp = /\{\{([\s\S]+?)\}\}/g;
var hasTemplate = function hasTemplate(s) {
  return s.match(exp);
};
var findTemplate = function findTemplate(s) {
  var m = exp.exec(s);
  return m ? m[1] : '';
};

var parseTemplate = function parseTemplate(path, param) {
  var url = path;

  if ((0, _isString2.default)(url) && (0, _isPlainObject2.default)(param)) {
    var key = findTemplate(url);
    while (key) {
      var value = param[key] || '';
      url = url.replace('{{' + key + '}}', value);
      key = findTemplate(url);
    }
  }

  return url;
};

/**
 * 创建API实例
 * @function createAPI
 * @memberOf fe-lib.FetchRequest
 * @param method - get、post、delete等。请使用枚举FetchRequest.Consts.HttpMethods
 * @param path - resource url
 * @param fetchConfig - request config对象，包活headers， body
 * @param templateHandler - 替换url中变量的函数
 */

exports.default = function (method, path, fetchConfig, templateHandler) {
  return function (params, config) {
    var url = path;
    var finalConfig = {};
    var finalTemplateHandler = templateHandler;

    if ((0, _isFunction2.default)(fetchConfig)) {
      finalTemplateHandler = fetchConfig;
    } else if ((0, _isObject2.default)(fetchConfig)) {
      finalConfig = fetchConfig;
    }

    if (hasTemplate(url) && !(0, _isFunction2.default)(finalTemplateHandler)) {
      finalTemplateHandler = parseTemplate;
    }

    if ((0, _isFunction2.default)(finalTemplateHandler)) {
      url = finalTemplateHandler(url, params);
    } else if ((0, _isObject2.default)(params)) {
      finalConfig = (0, _merge2.default)({}, finalConfig, params);
    }

    if ((0, _isObject2.default)(config)) {
      finalConfig = (0, _merge2.default)({}, finalConfig, config);
    }

    return _customRequest2.default.instance[method](url, finalConfig);
  };
};